//
//  ViewController.m
//  CCBluetooth
//
//  Created by zjh on 2021/8/31.
//

#import "ViewController.h"
#import "CCCell.h"
#import "CCBluetooth.h"
#import "CCFilter.h"
#import "CCAuthentication.h"
#import "CCPeripheral+Selected.h"
#import "CCDualModule.h"
@interface ViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tbv;
@property (nonatomic, strong) UIButton *btn;
@property (nonatomic, strong) NSArray <CCPeripheral *>*peripherals;
@property (nonatomic, strong) dispatch_semaphore_t lock;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(peripheralChange) name:CCBluetoothPeripheralsChangeNotifyKey object:nil];
    self.view.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.tbv];
    [self.view addSubview:self.btn];
    self.lock = dispatch_semaphore_create(1);
    [self configBluetooth];
//    [[CCBluetooth share] startScanAndStopAfterDelay:5];
    self.peripherals = [[CCBluetooth share] peripherals];
    // Do any additional setup after loading the view.
}
- (void)configBluetooth {
//
    //双模项目
//    [[CCDualModule share] addObserver];
//    [CCBluetooth registerQueue:dispatch_get_global_queue(0, 0)];//线程注册
//    [CCBluetooth share].filterProtocol = (id<CCFilterProtocol>)[[CCFilter alloc] init];
//    [CCBluetooth share].authProtocol = (id<CCAuthProtocol>)[[CCAuthentication alloc] init];//认证的实现
//    [[CCBluetooth share] addDelegate:self];//代理
    
    //灯项目
    [CCBluetooth registerServices:@[[CBUUID UUIDWithString:UUID_SERVICE]]];
    [CCBluetooth registerQueue:dispatch_get_global_queue(0, 0)];//线程注册
    [CCBluetooth share].filterProtocol = (id<CCFilterProtocol>)[[CCFilter alloc] init];
    [CCBluetooth share].authProtocol = (id<CCAuthProtocol>)[[CCAuthentication alloc] init];//认证的实现
    [[CCBluetooth share] addDelegate:self];//代理
}
- (void)btnAction{
    for (CCPeripheral *per in self.peripherals) {
        if (per.selected) {
            per.selected = NO;
            if (per.state == CCPeripheralStateNone) {
                [[CCBluetooth share] connect:per];
            }else if(per.state == CCPeripheralStateConnected){
                [[CCBluetooth share] disconnect:per];
            }
        }
    }
}

//- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
//    switch (central.state) {
//        case CBManagerStatePoweredOn:
//            [[CCBluetooth share] startScanAndStopAfterDelay:5];
//            break;
//
//        default:
//            break;
//    }
//}

- (void)peripheralChange {
    dispatch_semaphore_wait(self.lock, DISPATCH_TIME_FOREVER);
    self.peripherals = [[CCBluetooth share] peripherals];
    dispatch_main_async_safe(^{
        [self.tbv reloadData];
    });
    dispatch_semaphore_signal(self.lock);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.peripherals.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CCCell *cell = [tableView dequeueReusableCellWithIdentifier:CCCellKey];
    cell.selectedImgView.hidden = !self.peripherals[indexPath.row].selected;
    if (self.peripherals[indexPath.row].state == CCPeripheralStateConnectting) {
        [cell.indicatorView startAnimating];
    }else{
        [cell.indicatorView stopAnimating];
    }
    cell.titlelb.text = (self.peripherals[indexPath.row].state == CCPeripheralStateConnected) ? [NSString stringWithFormat:@"%@--已连接",self.peripherals[indexPath.row].name] : self.peripherals[indexPath.row].name;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    dispatch_semaphore_wait(self.lock, DISPATCH_TIME_FOREVER);
    if (self.peripherals[indexPath.row].state != CCPeripheralStateConnectting) {
        self.peripherals[indexPath.row].selected = !self.peripherals[indexPath.row].selected;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
    dispatch_semaphore_signal(self.lock);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
- (UITableView *)tbv {
    if (!_tbv) {
        _tbv = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 120)];
        _tbv.delegate = self;
        _tbv.dataSource = self;
        _tbv.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tbv.backgroundColor = [UIColor whiteColor];
        [_tbv registerClass:CCCell.class forCellReuseIdentifier:CCCellKey];
    }
    return _tbv;
}

- (UIButton *)btn {
    if (!_btn) {
        _btn = [[UIButton alloc] init];
        [_btn setTitle:@"连接" forState:UIControlStateNormal];
        [_btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _btn.backgroundColor = UIColor.purpleColor;
        _btn.frame = CGRectMake(50, ScreenHeight - 100 , ScreenWidth - 100, 50);
        _btn.layer.cornerRadius = 5;
        [_btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn;
}
@end
